package com.bdqn.tour.servlet.Gyh;

import com.alibaba.fastjson.JSON;
import com.bdqn.tour.pojo.User;
import com.bdqn.tour.service.GyhLoginservice;
import com.bdqn.tour.service.impl.GyhLoginserviceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * packageName com.csdj.web
 *
 * @author winver
 * @version 1.0
 * @className GyhSendSMSServlet
 * @date 2024/12/17
 * @description TODO
 */
@WebServlet("/sendSms")
public class GyhSendSMSServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.setCharacterEncoding("utf-8");
       resp.setCharacterEncoding("utf-8");
       resp.setContentType("text/plain;charset=utf-8");
       //获取手机号码
        String phone = req.getParameter("phone");
       //从数据库里判断是否存在在手机号
        GyhLoginservice service = new GyhLoginserviceImpl();
       User user = service.getLoginCheck(phone);
       //编写输出语句resp.getWriter()
        PrintWriter out = resp.getWriter();
        Map<String,Object> map = new HashMap<>();
       if (user != null){

           //随机生成一个数字验证码
           String valCode = getValCode();
           System.out.println("验证码:" + valCode);

           //发送短信
//        if (SMSUtil.sendSms(phone,valCode)) {
           if (true) {
               map.put("code","0000");
               //在会话中共享验证码，方便等会验证
               req.getSession().setAttribute(phone,valCode);
               req.getSession().setAttribute("user",user);
           }else{
               map.put("code","1001");
           }
       }else {
           map.put("code","1001");
       }

        //转成字符串
        String json = JSON.toJSONString(map);
        out.print(json);
        out.close();

    }

    public String getValCode(){
        StringBuffer valCode = new StringBuffer();
        for(int i = 0 ; i < 4 ; i ++){
            valCode.append((int)(Math.random() * 10));
        }
        return valCode.toString();
    }
}
